package com.hippo.provider.config;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0.0
 * @auther tangxl
 * @Date 2023/6/7/007 21:19
 */
public class ExportInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 如果不是方法
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        // 获取注解
        Export export = ((HandlerMethod)handler).getMethodAnnotation(Export.class);
        // 判断方法上是否有@Export注解
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        if (export!=null) {
            if (export.value().getCode().equals("import")) {
                // 导入
                System.out.println("导入");
                // 通过request获取multipartFile文件
                MultipartResolver resolver = new StandardServletMultipartResolver();
                MultipartHttpServletRequest mRequest = resolver.resolveMultipart(request);
                MultiValueMap<String, MultipartFile> multiFileMap = mRequest.getMultiFileMap();
                multiFileMap.entrySet().stream().forEach(o->{
                    List<MultipartFile> files = o.getValue();
                    files.stream().forEach(file-> {
                        String fileName = file.getOriginalFilename();
                        // 保存文件
                        try(
                                OutputStream outputStream = new FileOutputStream("D:\\Tools\\workspace\\learning\\java-study\\study-services\\service-provider\\src\\main\\resources\\saveFile\\"+fileName );
                                InputStream inputStream = file.getInputStream();
                        ) {
                            // 写入文件
                            byte[] bytes = new byte[1024];
                            int len = 0;
                            while ((len = inputStream.read(bytes)) != -1) {
                                outputStream.write(bytes, 0, len);
                            }
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                });

            }
        }
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (!(handler instanceof HandlerMethod)){
            return ;
        }
        // 获取注解
        Export export = ((HandlerMethod)handler).getMethodAnnotation(Export.class);
        // 判断方法上是否有@Export注解
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        // 判断方法上是否有@Export注解
        if (export!=null) {
            if (export.value().getCode().equals("export")) {
                // 导出
                System.out.println("导出");
                // 获取文件名
                response.getHeaders("Content-Disposition");
                String fileHeader = response.getHeader("Content-Disposition");
                String fileName = fileHeader.substring(fileHeader.indexOf("filename=") , fileHeader.length());
                // 获取文件类型
                String fileType = response.getContentType();
                // 获取文件大小
                String fileSize = String.valueOf(response.getBufferSize());
                // 保存文件
                try (
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        OutputStream os = new FileOutputStream("D:/迅雷下载/1.docx" );
                        ServletOutputStream outputStream = response.getOutputStream();
                        ){
                    // outputStream转inputStream
                    //此时有了byteArrayOutputStream输出流数据，将数据返回给response的输出流。
                    byteArrayOutputStream.writeTo(outputStream);
                    byte[] buffer = byteArrayOutputStream.toByteArray();
                    InputStream is = new ByteArrayInputStream(buffer);
                    // 写入文件
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = is.read(bytes)) != -1) {
                        os.write(bytes, 0, len);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        try(
                OutputStream os = new FileOutputStream("D:/迅雷下载/2.docx");
                InputStream is = new FileInputStream("D:/迅雷下载/1.docx");
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream()
                ){
            IOUtils.copy(is, os);
            byteArrayOutputStream.writeTo(os);
            System.out.println(1);
        }catch (Exception e) {

        }
    }
}

